home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Python 1.1 / Lib / ftplib.py < prev    next >
Encoding:
Python Source  |  1994-08-01  |  11.3 KB  |  416 lines  |  [TEXT/R*ch]

  1. # An FTP client class.  Based on RFC 959: File Transfer Protocol
  2. # (FTP), by J. Postel and J. Reynolds
  3.  
  4. # Changes and improvements suggested by Steve Majewski
  5.  
  6.  
  7. # Example:
  8. #
  9. # >>> from ftplib import FTP
  10. # >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
  11. # >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
  12. # >>> ftp.retrlines('LIST') # list directory contents
  13. # total 43
  14. # d--x--x--x   2 root     root         512 Jul  1 16:50 bin
  15. # d--x--x--x   2 root     root         512 Sep 16  1991 etc
  16. # drwxr-xr-x   2 root     ftp        10752 Sep 16  1991 lost+found
  17. # drwxr-srwt  15 root     ftp        10240 Nov  5 20:43 pub
  18. # >>> ftp.quit()
  19. #
  20. # To download a file, use ftp.retrlines('RETR ' + filename),
  21. # or ftp.retrbinary() with slightly different arguments.
  22. # To upload a file, use ftp.storlines() or ftp.storbinary(), which have
  23. # an open file as argument.
  24. # The download/upload functions first issue appropriate TYPE and PORT
  25. # commands.
  26.  
  27.  
  28. import os
  29. import sys
  30. import string
  31.  
  32. # Import SOCKS module if it exists, else standard socket module socket
  33. try:
  34.     import SOCKS; socket = SOCKS
  35. except ImportError:
  36.     import socket
  37.  
  38.  
  39. # Magic number from <socket.h>
  40. MSG_OOB = 0x1                # Process data out of band
  41.  
  42.  
  43. # The standard FTP server control port
  44. FTP_PORT = 21
  45.  
  46.  
  47. # Exception raised when an error or invalid response is received
  48. error_reply = 'ftplib.error_reply'    # unexpected [123]xx reply
  49. error_temp = 'ftplib.error_temp'    # 4xx errors
  50. error_perm = 'ftplib.error_perm'    # 5xx errors
  51. error_proto = 'ftplib.error_proto'    # response does not begin with [1-5]
  52.  
  53.  
  54. # All exceptions (hopefully) that may be raised here and that aren't
  55. # (always) programming errors on our side
  56. all_errors = (error_reply, error_temp, error_perm, error_proto, \
  57.           socket.error, IOError)
  58.  
  59.  
  60. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  61. CRLF = '\r\n'
  62.  
  63.  
  64. # The class itself
  65. class FTP:
  66.  
  67.     # New initialization method (called by class instantiation)
  68.     # Initialize host to localhost, port to standard ftp port
  69.     # Optional arguments are host (for connect()),
  70.     # and user, passwd, acct (for login())
  71.     def __init__(self, host = '', user = '', passwd = '', acct = ''):
  72.         # Initialize the instance to something mostly harmless
  73.         self.debugging = 0
  74.         self.host = ''
  75.         self.port = FTP_PORT
  76.         self.sock = None
  77.         self.file = None
  78.         self.welcome = None
  79.         if host:
  80.             self.connect(host)
  81.             if user: self.login(user, passwd, acct)
  82.  
  83.     # Connect to host.  Arguments:
  84.     # - host: hostname to connect to (default previous host)
  85.     # - port: port to connect to (default previous port)
  86.     def connect(self, host = '', port = 0):
  87.         if host: self.host = host
  88.         if port: self.port = port
  89.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  90.         self.sock.connect(self.host, self.port)
  91.         self.file = self.sock.makefile('r')
  92.         self.welcome = self.getresp()
  93.  
  94.     # Get the welcome message from the server
  95.     # (this is read and squirreled away by connect())
  96.     def getwelcome(self):
  97.         if self.debugging: print '*welcome*', `self.welcome`
  98.         return self.welcome
  99.  
  100.     # Set the debugging level.  Argument level means:
  101.     # 0: no debugging output (default)
  102.     # 1: print commands and responses but not body text etc.
  103.     # 2: also print raw lines read and sent before stripping CR/LF
  104.     def set_debuglevel(self, level):
  105.         self.debugging = level
  106.     debug = set_debuglevel
  107.  
  108.     # Internal: send one line to the server, appending CRLF
  109.     def putline(self, line):
  110.         line = line + CRLF
  111.         if self.debugging > 1: print '*put*', `line`
  112.         self.sock.send(line)
  113.  
  114.     # Internal: send one command to the server (through putline())
  115.     def putcmd(self, line):
  116.         if self.debugging: print '*cmd*', `line`
  117.         self.putline(line)
  118.  
  119.     # Internal: return one line from the server, stripping CRLF.
  120.     # Raise EOFError if the connection is closed
  121.     def getline(self):
  122.         line = self.file.readline()
  123.         if self.debugging > 1:
  124.             print '*get*', `line`
  125.         if not line: raise EOFError
  126.         if line[-2:] == CRLF: line = line[:-2]
  127.         elif line[-1:] in CRLF: line = line[:-1]
  128.         return line
  129.  
  130.     # Internal: get a response from the server, which may possibly
  131.     # consist of multiple lines.  Return a single string with no
  132.     # trailing CRLF.  If the response consists of multiple lines,
  133.     # these are separated by '\n' characters in the string
  134.     def getmultiline(self):
  135.         line = self.getline()
  136.         if line[3:4] == '-':
  137.             code = line[:3]
  138.             while 1:
  139.                 nextline = self.getline()
  140.                 line = line + ('\n' + nextline)
  141.                 if nextline[:3] == code and \
  142.                     nextline[3:4] <> '-':
  143.                     break
  144.         return line
  145.  
  146.     # Internal: get a response from the server.
  147.     # Raise various errors if the response indicates an error
  148.     def getresp(self):
  149.         resp = self.getmultiline()
  150.         if self.debugging: print '*resp*', `resp`
  151.         self.lastresp = resp[:3]
  152.         c = resp[:1]
  153.         if c == '4':
  154.             raise error_temp, resp
  155.         if c == '5':
  156.             raise error_perm, resp
  157.         if c not in '123':
  158.             raise error_proto, resp
  159.         return resp
  160.  
  161.     # Expect a response beginning with '2'
  162.     def voidresp(self):
  163.         resp = self.getresp()
  164.         if resp[0] <> '2':
  165.             raise error_reply, resp
  166.  
  167.     # Abort a file transfer.  Uses out-of-band data.
  168.     # This does not follow the procedure from the RFC to send Telnet
  169.     # IP and Synch; that doesn't seem to work with the servers I've
  170.     # tried.  Instead, just send the ABOR command as OOB data.
  171.     def abort(self):
  172.         line = 'ABOR' + CRLF
  173.         if self.debugging > 1: print '*put urgent*', `line`
  174.         self.sock.send(line, MSG_OOB)
  175.         resp = self.getmultiline()
  176.         if resp[:3] not in ('426', '226'):
  177.             raise error_proto, resp
  178.  
  179.     # Send a command and return the response
  180.     def sendcmd(self, cmd):
  181.         self.putcmd(cmd)
  182.         return self.getresp()
  183.  
  184.     # Send a command and expect a response beginning with '2'
  185.     def voidcmd(self, cmd):
  186.         self.putcmd(cmd)
  187.         self.voidresp()
  188.  
  189.     # Send a PORT command with the current host and the given port number
  190.     def sendport(self, port):
  191.         hostname = socket.gethostname()
  192.         hostaddr = socket.gethostbyname(hostname)
  193.         hbytes = string.splitfields(hostaddr, '.')
  194.         pbytes = [`port/256`, `port%256`]
  195.         bytes = hbytes + pbytes
  196.         cmd = 'PORT ' + string.joinfields(bytes, ',')
  197.         self.voidcmd(cmd)
  198.  
  199.     # Create a new socket and send a PORT command for it
  200.     def makeport(self):
  201.         global nextport
  202.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  203.         sock.listen(1)
  204.         host, port = sock.getsockname()
  205.         resp = self.sendport(port)
  206.         return sock
  207.  
  208.     # Send a port command and a transfer command, accept the connection
  209.     # and return the socket for the connection
  210.     def transfercmd(self, cmd):
  211.         sock = self.makeport()
  212.         resp = self.sendcmd(cmd)
  213.         if resp[0] <> '1':
  214.             raise error_reply, resp
  215.         conn, sockaddr = sock.accept()
  216.         return conn
  217.  
  218.     # Login, default anonymous
  219.     def login(self, user = '', passwd = '', acct = ''):
  220.         if not user: user = 'anonymous'
  221.         if user == 'anonymous' and passwd in ('', '-'):
  222.             thishost = socket.gethostname()
  223.             if os.environ.has_key('LOGNAME'):
  224.                 realuser = os.environ['LOGNAME']
  225.             elif os.environ.has_key('USER'):
  226.                 realuser = os.environ['USER']
  227.             else:
  228.                 realuser = 'anonymous'
  229.             passwd = passwd + realuser + '@' + thishost
  230.         resp = self.sendcmd('USER ' + user)
  231.         if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
  232.         if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
  233.         if resp[0] <> '2':
  234.             raise error_reply, resp
  235.  
  236.     # Retrieve data in binary mode.
  237.     # The argument is a RETR command.
  238.     # The callback function is called for each block.
  239.     # This creates a new port for you
  240.     def retrbinary(self, cmd, callback, blocksize):
  241.         self.voidcmd('TYPE I')
  242.         conn = self.transfercmd(cmd)
  243.         while 1:
  244.             data = conn.recv(blocksize)
  245.             if not data:
  246.                 break
  247.             callback(data)
  248.         conn.close()
  249.         self.voidresp()
  250.  
  251.     # Retrieve data in line mode.
  252.     # The argument is a RETR or LIST command.
  253.     # The callback function is called for each line, with trailing
  254.     # CRLF stripped.  This creates a new port for you.
  255.     # print_lines is the default callback 
  256.     def retrlines(self, cmd, callback = None):
  257.         if not callback: callback = print_line
  258.         resp = self.sendcmd('TYPE A')
  259.         conn = self.transfercmd(cmd)
  260.         fp = conn.makefile('r')
  261.         while 1:
  262.             line = fp.readline()
  263.             if not line:
  264.                 break
  265.             if line[-2:] == CRLF:
  266.                 line = line[:-2]
  267.             elif line[:-1] == '\n':
  268.                 line = line[:-1]
  269.             callback(line)
  270.         fp.close()
  271.         conn.close()
  272.         self.voidresp()
  273.  
  274.     # Store a file in binary mode
  275.     def storbinary(self, cmd, fp, blocksize):
  276.         self.voidcmd('TYPE I')
  277.         conn = self.transfercmd(cmd)
  278.         while 1:
  279.             buf = fp.read(blocksize)
  280.             if not buf: break
  281.             conn.send(buf)
  282.         conn.close()
  283.         self.voidresp()
  284.  
  285.     # Store a file in line mode
  286.     def storlines(self, cmd, fp):
  287.         self.voidcmd('TYPE A')
  288.         conn = self.transfercmd(cmd)
  289.         while 1:
  290.             buf = fp.readline()
  291.             if not buf: break
  292.             if buf[-2:] <> CRLF:
  293.                 if buf[-1] in CRLF: buf = buf[:-1]
  294.                 buf = buf + CRLF
  295.             conn.send(buf)
  296.         conn.close()
  297.         self.voidresp()
  298.  
  299.     # Return a list of files in a given directory (default the current)
  300.     def nlst(self, *args):
  301.         cmd = 'NLST'
  302.         for arg in args:
  303.             cmd = cmd + (' ' + arg)
  304.         files = []
  305.         self.retrlines(cmd, files.append)
  306.         return files
  307.  
  308.     # List a directory in long form.  By default list current directory
  309.     # to stdout.  Optional last argument is callback function;
  310.     # all non-empty arguments before it are concatenated to the
  311.     # LIST command.  (This *should* only be used for a pathname.)
  312.     def dir(self, *args):
  313.         cmd = 'LIST' 
  314.         func = None
  315.         if args[-1:] and type(args[-1]) != type(''):
  316.             args, func = args[:-1], args[-1]
  317.         for arg in args:
  318.             if arg:
  319.                 cmd = cmd + (' ' + arg) 
  320.         self.retrlines(cmd, func)
  321.  
  322.     # Rename a file
  323.     def rename(self, fromname, toname):
  324.         resp = self.sendcmd('RNFR ' + fromname)
  325.         if resp[0] <> '3':
  326.             raise error_reply, resp
  327.         self.voidcmd('RNTO ' + toname)
  328.  
  329.     # Change to a directory
  330.     def cwd(self, dirname):
  331.         if dirname == '..':
  332.             try:
  333.                 self.voidcmd('CDUP')
  334.                 return
  335.             except error_perm, msg:
  336.                 if msg[:3] != '500':
  337.                     raise error_perm, msg
  338.         cmd = 'CWD ' + dirname
  339.         self.voidcmd(cmd)
  340.  
  341.     # Retrieve the size of a file
  342.     def size(self, filename):
  343.         resp = self.sendcmd('SIZE ' + filename)
  344.         if resp[:3] == '213':
  345.             return string.atoi(string.strip(resp[3:]))
  346.  
  347.     # Make a directory, return its full pathname
  348.     def mkd(self, dirname):
  349.         resp = self.sendcmd('MKD ' + dirname)
  350.         return parse257(resp)
  351.  
  352.     # Return current wording directory
  353.     def pwd(self):
  354.         resp = self.sendcmd('PWD')
  355.         return parse257(resp)
  356.  
  357.     # Quit, and close the connection
  358.     def quit(self):
  359.         self.voidcmd('QUIT')
  360.         self.close()
  361.  
  362.     # Close the connection without assuming anything about it
  363.     def close(self):
  364.         self.file.close()
  365.         self.sock.close()
  366.         del self.file, self.sock
  367.  
  368.  
  369. # Parse a response type 257
  370. def parse257(resp):
  371.     if resp[:3] <> '257':
  372.         raise error_reply, resp
  373.     if resp[3:5] <> ' "':
  374.         return '' # Not compliant to RFC 959, but UNIX ftpd does this
  375.     dirname = ''
  376.     i = 5
  377.     n = len(resp)
  378.     while i < n:
  379.         c = resp[i]
  380.         i = i+1
  381.         if c == '"':
  382.             if i >= n or resp[i] <> '"':
  383.                 break
  384.             i = i+1
  385.         dirname = dirname + c
  386.     return dirname
  387.  
  388. # Default retrlines callback to print a line
  389. def print_line(line):
  390.     print line
  391.  
  392.  
  393. # Test program.
  394. # Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
  395. def test():
  396.     import marshal
  397.     debugging = 0
  398.     while sys.argv[1] == '-d':
  399.         debugging = debugging+1
  400.         del sys.argv[1]
  401.     host = sys.argv[1]
  402.     ftp = FTP(host)
  403.     ftp.set_debuglevel(debugging)
  404.     ftp.login()
  405.     for file in sys.argv[2:]:
  406.         if file[:2] == '-l':
  407.             ftp.dir(file[2:])
  408.         elif file[:2] == '-d':
  409.             cmd = 'CWD'
  410.             if file[2:]: cmd = cmd + ' ' + file[2:]
  411.             resp = ftp.sendcmd(cmd)
  412.         else:
  413.             ftp.retrbinary('RETR ' + file, \
  414.                        sys.stdout.write, 1024)
  415.     ftp.quit()
  416.